// 全局变量
var studentPage = 1;
var pageSize = 5;
var isStudentSearch = 0;
var offset1=(studentPage-1)*pageSize
var studentSearchData={
    id: 0,          // 教师ID（登录后赋值）
    offset: offset1,      // 分页偏移
    pageSize: pageSize     // 分页大小
};
var studentSerPage = 1;
// 当前激活的聊天面板（group/deepseek）
var activeChatPanel = 'group';
// 存储已显示的消息（避免重复显示）
let shownMessages = [];
const API_ROUTES = {
    GENERATE_LESSON_WITH_AI: '/deepseek/generate-teaching-plan'
};

// 当前学生信息存储
var currentStudentInfo = null;
var classChoose={
    id: 0,          // 教师ID（登录后赋值）
    offset: 0,      // 分页偏移
    pageSize: 100     // 分页大小
}
var lessonPage = 1;
var lessonPageSize = 5;
var isLessonSearch = 0;
var userInfoo = getUserInfo();
var tId = userInfoo.id;
var lessonSearchData = {
    id:tId,
    name: '',
    offset: 0,
    pageSize: pageSize
}


function detectByURL() {
    const path = window.location.pathname;
    if (path.includes('studentview')) {
        return 'studentview';
    } else if (path.includes('teacherview')) {
        return 'teacherview';
    }
    return 'unknown';
}
console.log(detectByURL())
// 检查登录状态
// 检查登录状态并显示用户名
if (sessionStorage.getItem('isLogin') == "true"&& JSON.parse(sessionStorage.getItem('userInfo') || '{}').type === 1) {
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
    $('.username').text(userInfo.name || '教师');
    if (userInfo.avatar) {
        $('.user-avatar').attr('src', userInfo.avatar);
    }
}
else if(detectByURL()==='teacherview'){
    // 未登录，跳转到登录页
    location.href = "/LLMTchStd/userlogin";
}

// 页面加载时初始化
$(document).ready(function() {

    // 初始化学生管理
    studentPageFunc();
    studentDataFunc();
    var userInfo = getUserInfo();
    var teId = userInfo.id;//登录的教师id
    classChoose.id=teId
    loadClassOptions();

    // 导航控制
    $('.sidebar-nav a').click(function(e) {
        e.preventDefault();
        $('.sidebar-nav li').removeClass('active');
        $(this).parent().addClass('active');
        $('.content-box').removeClass('active');
        $($(this).attr('href')).addClass('active');
        // 切换到聊天室时强制滚动到底部
        if ($(this).attr('href') === '#chatroom') {
            setTimeout(() => {
                scrollChatToBottom(activeChatPanel);
            }, 100);
        }
    });

    // 添加学生按钮点击事件
    $('#add-student').click(function() {
        $('#add-student-modal').addClass('show');
    });

    // 关闭添加学生模态框
    $('#cancel-student-btn, #add-student-modal .close-modal').click(function() {
        $('#add-student-modal').removeClass('show');
    });

    // 提交添加学生表单
    $('#student-form').submit(function(e) {
        e.preventDefault();
        addStudent();
    });

    // 关闭编辑学生模态框
    $('#cancel-edit-student-btn, #edit-student-modal .close-modal').click(function() {
        $('#edit-student-modal').removeClass('show');
    });

    // 提交编辑学生表单
    $('#edit-student-form').submit(function(e) {
        e.preventDefault();
        updateStudent();
    });

// 学生搜索按钮点击事件
    $('#search-student-btn').click(function() {
        isStudentSearch = 1;
        studentSerPage = 1;
        var name = $('#search-student-name').val().trim();
        var phone = $('#search-student-phone').val().trim();
        var classId = $('#class-filter').val();
        var offset = (studentSerPage - 1) * pageSize;

        studentSearchData = {
            "name": name,
            "phone": phone,
            "classId": classId,
            "offset": offset,
            "pageSize": pageSize
        };

        studentPageFunc();
        studentDataFunc();
    });

    // 点击模态框外部关闭
    $('.modal').click(function(e) {
        if (e.target === this) {
            $(this).removeClass('show');
        }
    });

    // 初始化聊天室
    initChatroom();
    initUserList();

    // 绑定学生删除按钮事件
    $(".studentContentBox").on("click", ".deleteStudent", function() {
        deleteStudent($(this).attr("index"));
    });

    // 绑定学生编辑按钮事件
    $(".studentContentBox").on("click", ".editStudent", function() {
        editStudent($(this).attr("index"));
    });

    // 学生页码切换
    $(".studentPageBox").on("click", ".page1", function() {
        if (isStudentSearch == 0) {
            if (studentPage == $(this).text()) {
                alert("该页已经是第" + $(this).text() + "页");
                return;
            }
            studentPage = $(this).text();
        } else {
            if (studentSerPage == $(this).text()) {
                alert("该页已经是第" + $(this).text() + "页");
                return;
            }
            studentSerPage = $(this).text();
            studentSearchData.offset = (studentSerPage - 1) * pageSize;
        }
        studentDataFunc();
        $(this).addClass("active");
        $(this).siblings().removeClass("active");
    });

    // 学生上一页
    $(".studentPageBox").on("click", ".prevPage", function() {
        if (isStudentSearch == 0) {
            if (studentPage == 1) {
                alert("已经是第一页");
                return;
            }
            studentPage--;
        } else {
            if (studentSerPage == 1) {
                alert("已经是第一页");
                return;
            }
            studentSerPage--;
            studentSearchData.offset = (studentSerPage - 1) * pageSize;
        }
        studentDataFunc();
        $(".studentPageBox .page1").removeClass("active");
        if (isStudentSearch == 0) {
            $(".studentPageBox .page1").eq(studentPage - 1).addClass("active");
        } else {
            $(".studentPageBox .page1").eq(studentSerPage - 1).addClass("active");
        }
    });

    // 学生下一页
    $(".studentPageBox").on("click", ".nextPage", function() {
        if (isStudentSearch == 0) {
            if (studentPage == $(".studentPageBox .page1").length) {
                alert("已经是最后一页");
                return;
            }
            studentPage++;
        } else {
            if (studentSerPage == $(".studentPageBox .page1").length) {
                alert("已经是最后一页");
                return;
            }
            studentSerPage++;
            studentSearchData.offset = (studentSerPage - 1) * pageSize;
        }
        studentDataFunc();
        $(".studentPageBox .page1").removeClass("active");
        if (isStudentSearch == 0) {
            $(".studentPageBox .page1").eq(studentPage - 1).addClass("active");
        } else {
            $(".studentPageBox .page1").eq(studentSerPage - 1).addClass("active");
        }
    });
});

// 加载班级选项
function loadClassOptions() {
    $.ajax({
        url: '/class/pageById',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(classChoose),
        success: function(value) {
            if (value.code == "0000") {
                var classes = value.data;
                // 更新所有班级选择器
                $('#class-filter, #student-class, #edit-student-class')
                    .empty()
                    .append('<option value="">请选择</option>');

                classes.forEach(clazz => {
                    const option = `<option value="${clazz.id}">${clazz.name}</option>`;
                    $('#class-filter').append(option);
                    $('#student-class, #edit-student-class').append(option);
                });
            }
        },
        error: function() {
            alert("加载班级选项失败");
        }
    });
}

// 学生分页函数
function studentPageFunc() {
    var url = isStudentSearch == 0 ? '/student/countById' : '/student/serCountById';
    var userInfo = getUserInfo();
    var id = userInfo.id;//登录的教师id

    if(isStudentSearch != 0){
        studentSearchData.id=id
    }

    var data =isStudentSearch == 0 ? JSON.stringify(id) : JSON.stringify(studentSearchData);
    //console.log(data)
    $.ajax({
        url: url,
        type: isStudentSearch == 0 ? 'POST' : 'POST',
        contentType: 'application/json',
        data: data,
        success: function(data) {
            if (data.code == "0000") {
                var value = data.data;
                $(".studentPageBox").empty();
                $(".studentPageBox").append("<button class='btn page prevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>");

                for (var i = 0; i < Math.ceil(value / pageSize); i++) {
                    const isActive = (isStudentSearch == 0 && i == studentPage - 1) ||
                        (isStudentSearch == 1 && i == studentSerPage - 1);
                    $(".studentPageBox").append(`<button class="btn page page1 ${isActive ? 'active' : ''}">${i + 1}</button>`);
                }

                $(".studentPageBox").append("<button class='btn page nextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>");
            } else {
                alert(data.msg);
            }
        },
        error: function() {
            alert("获取学生数量失败");
        }
    });
}

// 学生数据加载函数
function studentDataFunc() {
    var url = isStudentSearch == 0 ? '/student/pageById' : '/student/searchById';
    var userInfo = getUserInfo();
    var id = userInfo.id;//登录的教师id
    studentSearchData.id=id
    if(isStudentSearch==0){
        studentSearchData.offset=(studentPage-1)* pageSize
    }
    else {
        studentSearchData.offset=(studentSerPage-1)* pageSize
    }
    var data = JSON.stringify(studentSearchData);

    $.ajax({
        url: url,
        type: 'POST',
        contentType: 'application/json',
        data: data,
        success: function(value) {
            if (value.code == "0000") {
                var arr = value.data;
                $(".studentContentBox tbody").empty();

                if (arr.length === 0) {
                    // 添加搜索不到学生的提示行和返回按钮
                    $(".studentContentBox tbody").append(
                        '<tr><td colspan="8" style="text-align:center;">' +
                        (isStudentSearch == 1 ? '未搜索到符合条件的学生' : '暂无学生数据') + '<br>' +
                        '<button class="btn secondary reset-search-btn" style="margin-top:10px;">' +
                        '<i class="fas fa-arrow-left"></i> 返回全部学生' +
                        '</button>' +
                        '</td></tr>'
                    );

                    // 绑定返回按钮点击事件
                    $(".reset-search-btn").click(function() {
                        resetStudentSearch();
                    });

                    // 如果是搜索状态，显示弹窗提示
                    if (isStudentSearch == 1) {
                        alert('未搜索到符合条件的学生信息');
                    }
                    return;
                }

                arr.forEach((item, i) => {
                    $(".studentContentBox tbody").append(`<tr>
                        <td>${item.id}</td>
                        <td>${item.name}</td>
                        <td>${item.sno}</td>
                        <td>${item.sex}</td>
                        <td>${item.age}</td>
                        <td>${item.phone}</td>
                        <td>${item.className}</td>
                        <td class="action-buttons">
                            <button class="btn icon edit editStudent" title="编辑" index="${item.id}"><i class="fas fa-edit"></i></button>
                            <button class="btn icon delete deleteStudent" title="删除" index="${item.id}"><i class="fas fa-trash"></i></button>
                            <button class="btn icon ai aiAnalysis" title="AI分析" index="${item.id}"><i class="fas fa-brain"></i></button>
                        </td>
                    </tr>`);
                });
            } else if (value.code == "4003") { // 假设4003是"无数据"的错误码
                $(".studentContentBox tbody").empty().append(
                    '<tr><td colspan="8" style="text-align:center;">' +
                    '暂无对应学生信息<br>' +
                    '<button class="btn secondary reset-search-btn" style="margin-top:10px;">' +
                    '<i class="fas fa-arrow-left"></i> 返回全部学生' +
                    '</button>' +
                    '</td></tr>'
                );

                // 绑定返回按钮点击事件
                $(".reset-search-btn").click(function() {
                    resetStudentSearch();
                });

                if (isStudentSearch == 1) {
                    alert(value.msg || '未搜索到符合条件的学生信息');
                }
            } else {
                alert(value.msg || "获取学生列表失败");
            }
        },
        error: function() {
            alert("获取学生列表失败");
        }
    });
}
// 重置学生搜索状态
function resetStudentSearch() {
    isStudentSearch = 0;
    studentPage = 1;
    $('#search-student-name').val('');
    $('#search-student-phone').val('');
    $('#class-filter').val('');
    studentPageFunc();
    studentDataFunc();
}

// AI分析功能实现
$(".studentContentBox").on("click", ".aiAnalysis", function() {
    const $row = $(this).closest("tr");
    const studentId = $(this).attr("index");
    const studentName = $row.find("td:nth-child(2)").text();
    const studentClass = $row.find("td:nth-child(7)").text();
    const studentAge = $row.find("td:nth-child(5)").text();
    const studentGender = $row.find("td:nth-child(4)").text();

    // 存储当前学生信息用于下载
    currentStudentInfo = {
        id: studentId,
        name: studentName,
        class: studentClass,
        age: studentAge,
        gender: studentGender
    };

    // 显示加载状态
    $('#ai-analysis-modal').addClass('show');
    $('#ai-analysis-text').val('正在获取学生考试成绩并进行分析，请稍候...');

    // 1. 先获取学生的考试成绩
    $.ajax({
        url: '/exam-result/by-student/' + studentId,
        type: 'GET',
        success: function(examResultsResponse) {
            if (examResultsResponse.code === "0000" && examResultsResponse.data) {
                const examResults = examResultsResponse.data;

                // 2. 构建AI分析提示
                let prompt = `你是一位经验丰富的教育专家，请对以下学生进行全面的学习分析：
                学生ID：${studentId}
                姓名：${studentName}
                班级：${studentClass}
                年龄：${studentAge}
                性别：${studentGender}
                
                【考试成绩记录】
                ${formatExamResultsForAI(examResults)}
                
                请从以下几个方面进行分析：
                1. 学习成绩趋势分析（基于考试成绩）
                2. 学习习惯评估
                3. 潜在优势分析
                4. 可能存在的学习问题
                5. 个性化学习建议
                6. 未来发展方向预测
                
                要求：
                - 分析结果要详细、专业
                - 结合考试成绩数据给出具体分析
                - 给出具体可执行的建议
                - 使用中文输出
                - 格式清晰，分点列出`;

                // 3. 调用AI接口进行分析
                const requestData = {
                    studentId: studentId,
                    studentName: studentName,
                    studentClass: studentClass,
                    studentAge: studentAge,
                    studentGender: studentGender,
                    examResults: examResults
                };

                $.ajax({
                    url: '/deepseek/analyze-student-teacher',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(requestData),
                    success: function(response) {
                        if (response.code === "0000") {
                            const formattedText = `
                            【学生基础信息】
                            姓名：${studentName}
                            ID：${studentId}
                            班级：${studentClass}
                            年龄：${studentAge}
                            性别：${studentGender}
                            
                            【考试成绩概览】
                            ${formatExamResultsForDisplay(examResults)}
                            
                            【AI分析结果】
                            ${response.data}
                            
                            【分析时间】${new Date().toLocaleString()}
                            `;
                            $('#ai-analysis-text').val(formattedText.trim());
                        } else {
                            $('#ai-analysis-text').val('获取分析结果失败: ' + response.msg);
                        }
                    },
                    error: function(xhr) {
                        $('#ai-analysis-text').val('获取分析结果时发生错误: ' + (xhr.responseJSON?.msg || '服务器错误'));
                    }
                });
            } else {
                $('#ai-analysis-text').val('获取考试成绩失败: ' + (examResultsResponse.msg || '无考试成绩记录'));
            }
        },
        error: function(xhr) {
            $('#ai-analysis-text').val('获取考试成绩时发生错误: ' + (xhr.responseJSON?.msg || '服务器错误'));
        }
    });
});

// 格式化考试成绩供AI分析使用
function formatExamResultsForAI(examResults) {
    if (!examResults || examResults.length === 0) {
        return "暂无考试成绩记录";
    }

    let result = "";
    examResults.forEach((exam, index) => {
        result += `考试${index + 1}: 考试ID ${exam.examId}, 得分 ${exam.score}\n`;
    });
    return result;
}

// 格式化考试成绩供显示使用
function formatExamResultsForDisplay(examResults) {
    if (!examResults || examResults.length === 0) {
        return "暂无考试成绩记录";
    }

    let result = "";
    examResults.forEach((exam, index) => {
        result += `考试${index + 1}: 考试ID ${exam.examId}, 得分 ${exam.score}\n`;
    });

    // 计算平均分
    const averageScore = examResults.reduce((sum, exam) => sum + exam.score, 0) / examResults.length;
    result += `\n平均分: ${averageScore.toFixed(2)}`;

    // 计算最高分和最低分
    const maxScore = Math.max(...examResults.map(exam => exam.score));
    const minScore = Math.min(...examResults.map(exam => exam.score));
    result += `\n最高分: ${maxScore}, 最低分: ${minScore}`;

    return result;
}

// 下载分析结果
$('#download-analysis-btn').click(function() {
    if (!currentStudentInfo || !currentStudentInfo.id) {
        alert('请先选择学生进行AI分析');
        return;
    }

    const analysisText = $('#ai-analysis-text').val();
    if (!analysisText || analysisText.includes('正在获取')) {
        alert('请等待分析结果加载完成');
        return;
    }

    // 显示加载状态
    const $btn = $(this);
    $btn.html('<i class="fas fa-spinner fa-spin"></i> 正在生成报告...').prop('disabled', true);

    // 构建下载请求数据
    const downloadData = {
        studentInfo: currentStudentInfo,
        analysisContent: analysisText
    };

    // 调用下载接口
    $.ajax({
        url: '/deepseek/download-analysis',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(downloadData),
        xhrFields: {
            responseType: 'blob'
        },
        success: function(data, status, xhr) {
            let filename = currentStudentInfo.name + '-AI分析报告.docx';
            const disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('filename=') !== -1) {
                filename = disposition.split('filename=')[1].replace(/"/g, '');
            }

            const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            // 重置按钮状态
            $btn.html('<i class="fas fa-download"></i> 下载分析结果').prop('disabled', false);
        },
        error: function(xhr) {
            alert('下载失败: ' + (xhr.responseJSON?.msg || '服务器错误'));
            $btn.html('<i class="fas fa-download"></i> 下载分析结果').prop('disabled', false);
        }
    });
});

// 关闭模态框
$('#close-ai-modal').click(function() {
    $('#ai-analysis-modal').removeClass('show');
    currentStudentInfo = null;
});

// 添加学生
function addStudent() {
    var name = $("#student-name").val().trim();
    var sno = $("#student-id").val().trim();
    var sex = $("#student-gender").val();
    var age = $("#student-age").val().trim();
    var phone = $("#student-phone").val().trim();
    var classId = $("#student-class").val();

    var studentData = {
        "name": name,
        "sno": sno,
        "sex": sex,
        "age": parseInt(age),
        "phone": phone,
        "classId": classId,
        "password": 123456
    };

    $.ajax({
        url: "/student/add",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(studentData),
        success: function(value) {
            alert(value.msg);
            if (value.code == "0000") {
                $('#add-student-modal').removeClass('show');
                studentPageFunc();
                studentDataFunc();
            }
        },
        error: function() {
            alert("添加学生失败");
        }
    });
}

// 编辑学生
function editStudent(id) {
    $.ajax({
        url: "/student/edit",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(id),
        success: function(value) {
            if (value.code == "0000") {
                var student = value.data;
                $("#edit-student-id").val(student.id);
                $("#edit-student-name").val(student.name);
                $("#edit-student-Sno").val(student.sno);
                $("#edit-student-gender").val(student.sex);
                $("#edit-student-age").val(student.age);
                $("#edit-student-phone").val(student.phone);
                $("#edit-student-class").val(student.classId);
                $('#edit-student-modal').addClass('show');
            } else {
                alert(value.msg);
            }
        },
        error: function() {
            alert("获取学生信息失败");
        }
    });
}

// 更新学生
function updateStudent() {
    var id = $("#edit-student-id").val();
    var name = $("#edit-student-name").val().trim();
    var sno = $("#edit-student-Sno").val().trim();
    var sex = $("#edit-student-gender").val();
    var age = $("#edit-student-age").val().trim();
    var phone = $("#edit-student-phone").val().trim();
    var classId = $("#edit-student-class").val();

    var studentData = {
        "id": id,
        "name": name,
        "sno": sno,
        "sex": sex,
        "age": parseInt(age),
        "phone": phone,
        "classId": classId
    };

    $.ajax({
        url: "/student/update",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(studentData),
        success: function(value) {
            alert(value.msg);
            if (value.code == "0000") {
                $('#edit-student-modal').removeClass('show');
                studentPageFunc();
                studentDataFunc();
            }
        },
        error: function() {
            alert("更新学生信息失败");
        }
    });
}

// 删除学生
function deleteStudent(id) {
    if (confirm("确定要删除这位学生吗？")) {
        $.ajax({
            url: "/student/delete",
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(id),
            success: function(value) {
                alert(value.msg);
                if (value.code == "0000") {
                    studentPageFunc();
                    studentDataFunc();
                }
            },
            error: function() {
                alert("删除学生失败");
            }
        });
    }
}

// 初始化用户列表
function initUserList() {
    const userListContainer = document.getElementById('userListContainer');
    if (userListContainer) {
        userListContainer.innerHTML = '<div class="user-item system">等待连接...</div>';
    } else {
        console.error('未找到 userListContainer 元素');
    }
}

$('#create-lesson-plan').click(function() {
    $('#create-lesson-modal').addClass('show');
});

$('#refresh-lesson-plans').click(function() {
    loadLessonPlans();
});

$('#search-lesson-btn').click(function() {
    searchLessonPlans();
});

// 关闭预览模态框
$('#close-preview-btn').click(function() {
    $('#preview-lesson-modal').removeClass('show');
});

// 下载教案
$('#download-lesson-btn').click(function() {
    const planId = $(this).data('plan-id');
    downloadLessonPlan(planId);
});

$('.close-modal').click(function(e) {
    e.stopPropagation(); // 阻止事件冒泡
    $(this).closest('.modal').removeClass('show');
});

//AI
$('#ai-toggle-btn').click(function() {
    $('#ai-panel-container').toggleClass('show');
});

$(document).click(function(e) {
    if (!$(e.target).closest('#ai-panel-container').length &&
        !$(e.target).is('#ai-toggle-btn')) {
        $('#ai-panel-container').removeClass('show');
    }
});
// 加载教案列表
function loadLessonPlans() {
    const url = isLessonSearch == 0 ? '/teaching-plans/page' : '/teaching-plans/search';
    const data = isLessonSearch == 0 ?
        JSON.stringify({ offset: (lessonPage - 1) * lessonPageSize, pageSize: lessonPageSize, id: tId }) :
        JSON.stringify(lessonSearchData);

    $.ajax({
        url: url,
        type: 'POST',
        contentType: 'application/json',
        data: data,
        success: function(response) {
            if(response.code === '0000') {
                if (response.data.length === 0) {
                    // 如果没有数据，显示"暂无数据"提示和返回按钮
                    $('.lessonContentBox tbody').empty().append(
                        '<tr><td colspan="7" style="text-align:center;">' +
                        (isLessonSearch == 1 ? '未搜索到符合条件的教案' : '暂无教案数据') + '<br>' +
                        '<button class="btn secondary reset-search-btn" style="margin-top:10px;">' +
                        '<i class="fas fa-arrow-left"></i> 返回全部教案' +
                        '</button>' +
                        '</td></tr>'
                    );

                    // 绑定返回按钮点击事件
                    $(".reset-search-btn").click(function() {
                        resetLessonSearch();
                    });

                    // 如果是搜索状态，显示弹窗提示
                    if (isLessonSearch == 1) {
                        alert('未搜索到符合条件的教案');
                    }
                    return;
                }
                renderLessonPlans(response.data);
                loadLessonPageInfo();
            } else {
                alert(response.msg || '获取教案列表失败');
                $('.lessonContentBox tbody').empty().append(
                    '<tr><td colspan="7" style="text-align:center;">' +
                    (response.msg || '暂无教案数据') + '</td></tr>'
                );
            }
        },
        error: function(xhr) {
            alert('加载教案列表失败，请检查网络或登录状态');
            console.error('Error loading lesson plans:', xhr.status, xhr.statusText);
            $('.lessonContentBox tbody').empty().append(
                '<tr><td colspan="7" style="text-align:center;">加载教案失败</td></tr>'
            );
        }
    });
}

// 重置教案搜索状态
function resetLessonSearch() {
    isLessonSearch = 0;
    lessonPage = 1;
    $('#search-lesson-name').val('');
    loadLessonPlans();
}

// 加载教案分页信息
function loadLessonPageInfo() {
    var id=tId
    const url = isLessonSearch == 0 ? '/teaching-plans/count' : '/teaching-plans/search-count';
    const data = isLessonSearch == 0 ? JSON.stringify(id) : JSON.stringify({ name: lessonSearchData.name ,id:tId});

    $.ajax({
        url: url,
        type: isLessonSearch == 0 ? 'POST' : 'POST',
        contentType: 'application/json',
        data: data,
        success: function(data) {
            if (data.code == "0000") {
                var total = data.data;
                $(".lessonPageBox").empty();
                $(".lessonPageBox").append("<button class='btn page prevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>");

                for (var i = 0; i < Math.ceil(total / lessonPageSize); i++) {
                    const isActive = (isLessonSearch == 0 && i == lessonPage - 1) ||
                        (isLessonSearch == 1 && i == lessonSearchData.offset / lessonPageSize);
                    $(".lessonPageBox").append(`<button class="btn page page1 ${isActive ? 'active' : ''}">${i + 1}</button>`);
                }

                $(".lessonPageBox").append("<button class='btn page nextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>");
            } else {
                alert(data.msg);
            }
        },
        error: function() {
            alert("获取教案总数失败");
        }
    });
}
// 渲染教案列表
function renderLessonPlans(plans) {
    const $tbody = $('.lessonContentBox tbody');
    $tbody.empty();

    if (!plans || plans.length === 0) {
        $tbody.append('<tr><td colspan="7" style="text-align:center;">暂无教案数据</td></tr>');
        return;
    }

    plans.forEach(plan => {
        const createTime = new Date(plan.createTime).toLocaleString();
        const shortGoal = plan.goal ? (plan.goal.length > 30 ? plan.goal.substring(0, 30) + '...' : plan.goal) : '';
        const isExamText = plan.isExam === '1' ? '是' : '否';
        const creatorName = plan.teacherName || '未知教师';

        $tbody.append(`
            <tr>
                <td>${plan.id}</td>
                <td>${plan.name}</td>
                <td>${shortGoal}</td>
                <td>${isExamText}</td>
                <td>${creatorName}</td>
                <td>${createTime}</td>
                <td class="action-buttons">
                    <button class="btn icon preview" title="预览" onclick="previewLesson(${plan.id})"><i class="fas fa-eye"></i></button>
                    <button class="btn icon download" title="下载" onclick="downloadLessonPlan(${plan.id})"><i class="fas fa-download"></i></button>
                    <button class="btn icon delete" title="删除" onclick="deleteLessonPlan(${plan.id})"><i class="fas fa-trash"></i></button>
                </td>
            </tr>
        `);
    });
}

// 搜索教案（模糊查询）
function searchLessonPlans() {
    const name = $('#search-lesson-name').val().trim();
    if(!name) {
        isLessonSearch = 0;
        lessonPage = 1;
        loadLessonPlans();
        return;
    }

    isLessonSearch = 1;
    lessonSearchData = {
        id: tId,  // 添加教师ID
        name: name,
        offset: 0,
        pageSize: lessonPageSize
    };

    loadLessonPlans();
}


// 教案页码切换
$(".lessonPageBox").on("click", ".page1", function() {
    if (isLessonSearch == 0) {
        if (lessonPage == $(this).text()) {
            alert("该页已经是第" + $(this).text() + "页");
            return;
        }
        lessonPage = $(this).text();
    } else {
        const newPage = $(this).text();
        if (lessonSearchData.offset / lessonPageSize + 1 == newPage) {
            alert("该页已经是第" + newPage + "页");
            return;
        }
        lessonSearchData.offset = (newPage - 1) * lessonPageSize;
    }
    loadLessonPlans();
    $(this).addClass("active");
    $(this).siblings().removeClass("active");
});

// 教案上一页
$(".lessonPageBox").on("click", ".prevPage", function() {
    if (isLessonSearch == 0) {
        if (lessonPage == 1) {
            alert("已经是第一页");
            return;
        }
        lessonPage--;
    } else {
        if (lessonSearchData.offset <= 0) {
            alert("已经是第一页");
            return;
        }
        lessonSearchData.offset -= lessonPageSize;
    }
    loadLessonPlans();
    $(".lessonPageBox .page1").removeClass("active");
    const activeIndex = isLessonSearch == 0 ? lessonPage - 1 : lessonSearchData.offset / lessonPageSize;
    $(".lessonPageBox .page1").eq(activeIndex).addClass("active");
});

// 教案下一页
$(".lessonPageBox").on("click", ".nextPage", function() {
    if (isLessonSearch == 0) {
        if (lessonPage == $(".lessonPageBox .page1").length) {
            alert("已经是最后一页");
            return;
        }
        lessonPage++;
    } else {
        if (lessonSearchData.offset + lessonPageSize >= $(".lessonPageBox .page1").length * lessonPageSize) {
            alert("已经是最后一页");
            return;
        }
        lessonSearchData.offset += lessonPageSize;
    }
    loadLessonPlans();
    $(".lessonPageBox .page1").removeClass("active");
    const activeIndex = isLessonSearch == 0 ? lessonPage - 1 : lessonSearchData.offset / lessonPageSize;
    $(".lessonPageBox .page1").eq(activeIndex).addClass("active");
});

// 提交创建教案表单
$('#lesson-form').submit(function(e) {
    e.preventDefault();
    createLessonPlan();
});

function createLessonPlan() {
    const plan = {
        name: $('#lesson-name').val().trim(),
        goal: $('#lesson-objective').val().trim(),
        remark: $('#lesson-remark').val().trim(),
        isExam: $('#lesson-is-exam').val() // 直接传递字符串值
    };

    $.ajax({
        url: '/teaching-plans/create',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(plan),
        success: function(response) {
            alert(response.msg);
            if(response.code === '0000') {
                $('#create-lesson-modal').removeClass('show');
                loadLessonPlans();
            }
        },
        error: function() {
            alert('创建教案失败');
        }
    });
}

// 预览教案
function previewLesson(planId) {
    $.ajax({
        url: `/teaching-plans/preview/${planId}`,
        type: 'GET',
        success: function(response) {
            if(response.code === '0000') {
                const plan = response.data;
                const createTime = new Date(plan.createTime).toLocaleString();
                const isExamText = plan.isExam === '1' ? '是' : '否';
                const creatorName = plan.teacherName || '未知教师'; // 使用teacherName字段

                $('#preview-lesson-content').html(`
                    <h3>${plan.name}</h3>
                    <p><strong>创建人：</strong>${creatorName}</p>
                    <p><strong>创建时间：</strong>${createTime}</p>
                    <p><strong>是否考试：</strong>${isExamText}</p>
                    <div style="margin-top: 20px;">
                        <h4>教学目标：</h4>
                        <p>${plan.goal || '无'}</p>
                    </div>
                    <div style="margin-top: 20px;">
                        <h4>备注：</h4>
                        <p>${plan.remark || '无'}</p>
                    </div>
                `);

                $('#download-lesson-btn').data('plan-id', planId);
                $('#preview-lesson-modal').addClass('show');
            } else {
                alert(response.msg);
            }
        },
        error: function() {
            alert('获取教案详情失败');
        }
    });
}


// AI生成教案函数
function generateLessonWithAI() {
    const prompt = $('#lesson-ai-prompt').val().trim();
    if (!prompt) {
        alert('请输入生成提示词');
        return;
    }

    const btn = $('#generate-with-ai');
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 生成中...');

    $.ajax({
        url: '/deepseek/generate-teaching-plan',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ prompt: prompt }),
        success: function(response) {
            btn.prop('disabled', false).html('<i class="fas fa-sparkles"></i> 生成教案');

            if (response.code === '0000') {
                try {
                    const plan = JSON.parse(response.data);
                    $('#lesson-name').val(plan.name || '');
                    $('#lesson-objective').val(plan.goal || '');
                    $('#lesson-remark').val(plan.remark || '');
                    $('#lesson-is-exam').val(plan.isExam || '0');
                    $('#create-lesson-modal').addClass('show');
                    alert('AI教案已生成并填充到表单中！');
                } catch (e) {
                    alert('解析AI响应失败: ' + e.message);
                }
            } else {
                alert('生成失败: ' + response.msg);
            }
        },
        error: function(xhr) {
            btn.prop('disabled', false).html('<i class="fas fa-sparkles"></i> 生成教案');
            alert('请求失败: ' + xhr.statusText);
        }
    });
}
$('#generate-with-ai').click(generateLessonWithAI);

// 下载教案
function downloadLessonPlan(planId) {
    window.open(`/teaching-plans/download/${planId}`, '_blank');
}

// 删除教案
function deleteLessonPlan(planId) {
    if(confirm('确定要删除这个教案吗？')) {
        $.ajax({
            url: `/teaching-plans/delete/${planId}`,
            type: 'DELETE',
            success: function(response) {
                if(response.code === '0000') {
                    alert(response.msg);
                    loadLessonPlans();
                } else if(response.code === '1001') { // 假设1001是权限不足的错误码
                    alert('您没有权限删除此教案');
                } else {
                    alert(response.msg);
                }
            },
            error: function() {
                alert('删除教案失败');
            }
        });
    }
}

// 在页面加载时调用
$(document).ready(function() {
    loadLessonPlans();
});

// 聊天室相关逻辑
let ws = null;
let userInfo = null;

// 处理回车键发送消息（根据当前激活面板）
function handleEnterKey(e) {
    if (e.key === 'Enter' || e.keyCode === 13) {
        e.preventDefault();
        if (activeChatPanel === 'group') {
            sendGroupMessage();
        } else {
            sendDeepseekMessage();
        }
    }
}







// 初始化聊天室（绑定输入框事件）
function initChatroom() {
    checkLoginStatus();
    // 群聊输入框事件绑定
    const groupInput = document.getElementById('groupMessageInput');
    if (groupInput) {
        groupInput.removeEventListener('keypress', handleEnterKey);
        groupInput.addEventListener('keypress', handleEnterKey);
    }
    // DeepSeek输入框事件绑定
    const deepseekInput = document.getElementById('deepseekMessageInput');
    if (deepseekInput) {
        deepseekInput.removeEventListener('keypress', handleEnterKey);
        deepseekInput.addEventListener('keypress', handleEnterKey);
    }
}

// 检查登录状态
function checkLoginStatus() {
    const isLogin = sessionStorage.getItem('isLogin');
    userInfo = sessionStorage.getItem('userInfo') ? JSON.parse(sessionStorage.getItem('userInfo')) : null;
    if (!isLogin || !userInfo) {
        showMessage('系统提示', '使用默认身份进入聊天室', 'system', 'group');
        userInfo = { id: 'teacher_1', name: '张老师', type: 1 };
        connectWebSocket();
        return;
    }
    showMessage('系统提示', `用户【${userInfo.name}】准备连接...`, 'system', 'group');
    connectWebSocket();
}

// 连接WebSocket（群聊专用）
function connectWebSocket() {
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const baseUrl = `${wsProtocol}//${window.location.host}`;
    const wsPath = '/ws';
    const sockJsPath = '/ws/sockjs';

    try {
        ws = new WebSocket(`${baseUrl}${wsPath}`);
    } catch (e) {
        console.log('原生WebSocket不支持，尝试使用SockJS');
        ws = new SockJS(`${baseUrl}${sockJsPath}`);
    }

    ws.onopen = () => showMessage('系统提示', '连接成功，可以开始聊天了', 'system', 'group');
    ws.onmessage = function(event) {
        try {
            const message = JSON.parse(event.data);
            if (message.userList && Array.isArray(message.userList)) renderUserList(message.userList);
            if (message.content) {
                let userTypeText = userInfo.type === 0 ? "student" : "teacher";
                const isSelf = message.senderId === userInfo.id && message.senderType === userTypeText;
                showMessage(
                    message.senderName || '系统',
                    message.content,
                    isSelf ? 'self' : (message.senderType === 'system' ? 'system' : 'others'),
                    'group' // 群聊消息只显示在群聊面板
                );
            }
        } catch (e) {
            console.error('解析消息失败', e);
            showMessage('系统提示', '收到无效消息', 'system', 'group');
        }
    };
    ws.onclose = () => {
        showMessage('系统提示', '连接已关闭', 'system', 'group');
        const userListContainer = document.getElementById('userListContainer');
        if (userListContainer) {
            userListContainer.innerHTML = '<div class="user-item system">连接已关闭</div>';
        } else {
            console.error('未找到 userListContainer 元素');
        }
        setTimeout(() => {
            showMessage('系统提示', '尝试重新连接...', 'system', 'group');
            connectWebSocket();
        }, 10000);
    };
    ws.onerror = (error) => {
        console.error('WebSocket错误', error);
        showMessage('系统提示', '连接出错', 'system', 'group');
        const userListContainer = document.getElementById('userListContainer');
        if (userListContainer) {
            userListContainer.innerHTML = '<div class="user-item system">连接出错</div>';
        } else {
            console.error('未找到 userListContainer 元素');
        }
    };
}

// 渲染用户列表（群聊）
function renderUserList(userList) {
    const userListContainer = document.getElementById('userListContainer');
    if (userListContainer) {
        userListContainer.innerHTML = '';
    } else {
        console.error('未找到 userListContainer 元素');
    }

    if (userList.length === 0) {
        userListContainer.innerHTML = '<div class="user-item system">暂无在线用户</div>';
        return;
    }
    userList.forEach(user => {
        const userItem = document.createElement('div');
        const userType = user.type === '1' || user.type === 1 ? 'teacher' : 'student';
        userItem.className = `user-item ${userType}`;
        userItem.textContent = user.name;
        userListContainer.appendChild(userItem);
    });
}

// 发送群聊消息
function sendGroupMessage() {
    const input = document.getElementById('groupMessageInput');
    const content = input.value.trim();
    if (!content) { alert('请输入消息内容'); return; }
    if (!ws || (ws.readyState !== WebSocket.OPEN && ws.readyState !== 1)) {
        alert('连接未建立，请稍后再试'); return;
    }
    const message = {
        content: content,
        senderId: userInfo.id,
        senderName: userInfo.name,
        senderType: userInfo.type === 0 ? 'student' : 'teacher',
    };
    ws.send(JSON.stringify(message));
    input.value = '';
}

// 断开群聊连接
function closeGroupConnection() {
    if (ws) {
        ws.close();
        showMessage('系统提示', '已手动断开连接', 'system', 'group');
        const userListContainer = document.getElementById('userListContainer');
        if (userListContainer) { // 防御性检查，避免后续报错
            userListContainer.innerHTML = '<div class="user-item system">已断开连接</div>';
        } else {
            console.error('未找到 userListContainer 元素');
        }

    }
}

// 发送DeepSeek消息（带加载动画）
function sendDeepseekMessage() {
    const input = document.getElementById('deepseekMessageInput');
    const content = input.value.trim();
    if (!content) { alert('请输入消息内容'); return; }

    // 1. 显示用户消息
    showMessage(userInfo.name, content, 'self', 'deepseek');
    input.value = '';

    // 2. 调用后端接口
    $.ajax({
        url: '/deepseek/chat',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            content: content,
            userId: userInfo.id
        }),
        beforeSend: () => {
            // 显示加载动画
            const loadingId = showLoadingAnimation();
            window.deepseekLoading = {
                timer: startLoadingAnimation(loadingId),
                elementId: loadingId
            };
        },
        success: (response) => {
            // 清除加载动画
            clearLoadingAnimation();

            if (response.code === '0000' && response.data) {
                showMessage('DeepSeek', response.data, 'others', 'deepseek');
            } else {
                showMessage('系统', '获取回复失败: ' + (response.msg || '未知错误'), 'system', 'deepseek');
            }
        },
        error: (xhr) => {
            // 错误时清除动画
            clearLoadingAnimation();
            showMessage('系统', '接口调用失败，请稍后再试', 'system', 'deepseek');
            console.error('DeepSeek接口错误:', xhr);
        }
    });
}

/* 加载动画控制函数 */
function showLoadingAnimation() {
    const loadingId = 'deepseek-loading-' + Date.now();
    const messageElement = document.createElement('div');
    messageElement.id = loadingId;
    messageElement.className = 'message system';
    messageElement.innerHTML = `<strong>DeepSeek</strong>: <span class="loading-text">正在生成</span>`;
    const chatArea = document.getElementById('deepseekChatArea');
    if (chatArea) {
        chatArea.appendChild(messageElement);
        scrollChatToBottom('deepseek');
    }
    return loadingId;
}

function startLoadingAnimation(loadingId) {
    return setInterval(() => {}, 1000);
}

function clearLoadingAnimation() {
    if (window.deepseekLoading) {
        clearInterval(window.deepseekLoading.timer);
        const loadingElement = document.getElementById(window.deepseekLoading.elementId);
        if (loadingElement && loadingElement.parentNode) {
            loadingElement.parentNode.removeChild(loadingElement);
        }
        window.deepseekLoading = null;
    }
}

// 切换聊天面板（群聊/DeepSeek）
function switchChat(panelType) {
    if (panelType !== 'group' && panelType !== 'deepseek') return;

    activeChatPanel = panelType;
    // 更新标签样式
    $('.chat-tab').removeClass('active');
    $(`.chat-tab[onclick="switchChat('${panelType}')"]`).addClass('active');

    // 显示/隐藏对应面板
    document.querySelector('.group-chat-panel').style.display = panelType === 'group' ? 'flex' : 'none';
    document.querySelector('.deepseek-chat-panel').style.display = panelType === 'deepseek' ? 'flex' : 'none';

    // 切换面板后强制滚动到底部
    scrollChatToBottom(panelType);
}

// 显示消息
// 显示消息（移除去重逻辑）
function showMessage(sender, content, type, panel) {
    // 直接跳过去重判断，执行显示逻辑
    const chatAreaId = panel === 'group' ? 'groupChatArea' : 'deepseekChatArea';
    const chatArea = document.getElementById(chatAreaId);
    if (!chatArea) return;

    const messageWrapper = document.createElement('div');
    messageWrapper.style.overflow = 'hidden';

    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.innerHTML = `<strong>${sender}</strong><span class="content">${content}</span>`;

    messageWrapper.appendChild(messageDiv);
    chatArea.appendChild(messageWrapper);
    scrollChatToBottom(panel);
}

// 聊天区域滚动到底部（修复版）
function scrollChatToBottom(panelType) {
    const chatAreaId = panelType === 'group' ? 'groupChatArea' : 'deepseekChatArea';
    const chatArea = document.getElementById(chatAreaId);
    if (chatArea) {
        // 强制重绘后再滚动（解决动态内容高度计算延迟问题）
        chatArea.style.display = 'none';
        chatArea.offsetHeight; // 触发重绘
        chatArea.style.display = 'block';
        // 滚动到底部
        chatArea.scrollTop = chatArea.scrollHeight;
    }
}

//考试管理
var isSearch = 0;
var serPage = 1;

var examPage = 1;
var examData;

exPage();
var offset = (examPage - 1) * pageSize;
examData = {
    "offset": offset,
    "pageSize": pageSize
};
exData();

function exPage() {
    if (isSearch == 0) {
        $.ajax({
            url: '/exam/count',
            type: 'get',
            contentType: 'application/json',
            success: function(data) {
                if (data.code == "0000") {
                    var value = data.data;
                    $(".examPageBox").empty();
                    $(".examPageBox").append("<button class='btn page prevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>");
                    for (var i = 0; i < Math.ceil(value / pageSize); i++) {
                        if (i == examPage - 1) {
                            $(".examPageBox").append("<button class='btn page page1 active'>" + (i + 1) + "</button>");
                        } else {
                            $(".examPageBox").append("<button class='btn page page1'>" + (i + 1) + "</button>");
                        }
                    }
                    $(".examPageBox").append("<button class='btn page nextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>");
                } else {
                    alert(data.msg);
                }
            },
            error: function() {
                alert("出错了");
            }
        });
    } else {
        $.ajax({
            url: '/exam/serCount',
            type: 'post',
            contentType: 'application/json',
            data: JSON.stringify(examData),
            success: function(data) {
                if (data.code == "0000") {
                    var value = data.data;
                    $(".examPageBox").empty();
                    $(".examPageBox").append("<button class='btn page prevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>");
                    for (var i = 0; i < Math.ceil(value / pageSize); i++) {
                        if (i == serPage - 1) {
                            $(".examPageBox").append("<button class='btn page page1 active'>" + (i + 1) + "</button>");
                        } else {
                            $(".examPageBox").append("<button class='btn page page1'>" + (i + 1) + "</button>");
                        }
                    }
                    $(".examPageBox").append("<button class='btn page nextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>");
                } else {
                    alert(data.msg);
                }
            },
            error: function() {
                alert("出错了");
            }
        });
    }
}

function exData() {
    if (isSearch == 0) {
        offset = (examPage - 1) * pageSize;
        examData.offset = offset;
        $.ajax({
            url: '/exam/page',
            type: "post",
            contentType: 'application/json',
            data: JSON.stringify(examData),
            success: function(value) {
                if (value.code == "0000") {
                    var arr = value.data;
                    $(".examContentBox tbody").empty();
                    for (var i = 0; i < arr.length; i++) {
                        if(arr[i].id==null){
                            arr[i].id="暂无"
                            arr[i].createTime="暂无"
                            arr[i].creatorName="暂无"
                        }
                        $(".examContentBox tbody").append("<tr>" +
                            "<td>" + arr[i].id + "</td>" +
                            "<td>" + arr[i].createByName + "</td>" +
                            "<td>" + arr[i].createTime + "</td>" +
                            "<td>" + arr[i].creatorName + "</td>" +
                            "<td>" + arr[i].examCount + "</td>" +
                            "<td class='action-buttons'><button class='btn icon generate' title='生成试卷' index='"+arr[i].id+"' tpId='"+arr[i].createBy+"'><i class='fas fa-file-alt'></i></button>" +
                            "<button class='btn icon preview' title='预览' index='"+arr[i].id+"'><i class='fas fa-eye'></i></button>" +
                            "<button class='btn icon publish' title='发布考试' index='"+arr[i].id+"'><i class='fas fa-bullhorn'></i></button>"+
                            "</tr>"
                        );
                    }
                }
            },
            error: function() {
                alert("出错了");
            }
        });
    } else {
        offset = (serPage - 1) * pageSize;
        examData.offset = offset;
        $.ajax({
            url: '/exam/search',
            type: "post",
            contentType: 'application/json',
            data: JSON.stringify(examData),
            success: function(value) {
                if (value.code == "0000") {
                    var arr = value.data;
                    $(".examContentBox tbody").empty();
                    for (var i = 0; i < arr.length; i++) {
                        if(arr[i].id==null){
                            arr[i].id="暂无"
                            arr[i].createTime="暂无"
                            arr[i].creatorName="暂无"
                        }

                        $(".examContentBox tbody").append("<tr>" +
                            "<td>" + arr[i].id + "</td>" +
                            "<td>" + arr[i].createByName + "</td>" +
                            "<td>" + arr[i].createTime + "</td>" +
                            "<td>" + arr[i].creatorName + "</td>" +
                            "<td>" + arr[i].examCount + "</td>" +
                            "<td class='action-buttons'><button class='btn icon generate' title='生成试卷' index='"+arr[i].id+"' tpId='"+arr[i].createBy+"'><i class='fas fa-file-alt'></i></button>" +
                            "<button class='btn icon preview' title='预览' index='"+arr[i].id+"'><i class='fas fa-eye'></i></button>" +
                            "<button class='btn icon publish' title='发布考试' index='"+arr[i].id+"'><i class='fas fa-bullhorn'></i></button>"+
                            "</tr>"
                        );
                    }
                }
                else if(value.code=="4003"){
                    $(".examContentBox tbody").empty();
                    alert(value.msg)
                }
                else{
                    alert("出错了");
                }
            },
            error: function() {
                alert("出错了");
            }
        });
    }
}

$(".examRa").click(function() {
    var index = $(this).attr("index");

    //清除搜索框的内容
    $('#search-tp-name').val('');

    //搜索状态设置为0
    isSearch = 0;
    serPage = 1;

    exPage();
    exData();
});

//生成试卷弹框
$(".examContentBox tbody").on("click",".generate",function() {
    $('#generate-exam-modal').addClass('show');
    //给弹框里的生成试卷按钮加上试卷id
    // 获取当前点击按钮的index属性值
    var examId = $(this).attr('index');
    // 将获取到的index值设置到confirm-generate-exam按钮上
    $('#confirm-generate-exam').attr('index', examId);

    //给弹框里的生成试卷按钮加上教案id
    var tpId= $(this).attr('tpId');
    $('#confirm-generate-exam').attr('tpId', tpId);
})

//关闭弹窗（点击关闭按钮、取消按钮）
$('#generate-exam-modal .close-modal,#cancel-generate-exam-btn').click(function() {
    $('#generate-exam-modal').removeClass('show');
});

// 获取当前登录用户信息
function getUserInfo() {
    const userInfo = sessionStorage.getItem('userInfo');
    return userInfo ? JSON.parse(userInfo) : null;
}

//弹框里的生成考卷按钮
$('#confirm-generate-exam').click(function(){
    var generateData;
    var userInfo = getUserInfo();
    var creatorId = userInfo.id;
    var $this = $(this);
    var tpId = $this.attr('tpId');
    var choiceCount = parseInt($("#choice-count").val(), 10) || 0;
    var fillCount = parseInt($("#fill-count").val(), 10) || 0;
    var judgeCount = parseInt($("#judge-count").val(), 10) || 0;
    var essayCount = parseInt($("#essay-count").val(), 10) || 0;
    var calculateCount = parseInt($("#calculate-count").val(), 10) || 0;
    var examRemark = $("#exam-remark").val() || "";

    // 构建generateData（无需包含教案信息，后端查询）
    generateData = {
        creatorId: creatorId,
        creatorType: 1,
        createBy: tpId, // 仅传递教案ID
        choiceCount: choiceCount,
        fillCount: fillCount,
        judgeCount: judgeCount,
        essayCount: essayCount,
        calculateCount: calculateCount,
        remark: examRemark
    };

    // 判断操作类型
    if ($this.attr('index') == null) {
        generateData.way = 0;
    } else {
        generateData.way = 1;
        generateData.id = $this.attr('index');
    }


    $('#generate-exam-modal #progress-container').hide();

    // 保存原始按钮内容，用于恢复
    var originalBtnContent = $this.html();
    // 按钮设置为loading状态
    $this.html('<i class="fas fa-spinner fa-spin"></i> 正在生成...').attr('disabled', true);

    // 生成试卷AJAX请求
    $.ajax({
        url: "/deepseek/generate-exam",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify({ generateData: generateData }),
        success: function (value) {
            // 恢复按钮状态
            $this.html(originalBtnContent).attr('disabled', false);

            alert(value.msg);
            if (value.code == "0000") {
                // 生成成功，关闭弹框
                $('#generate-exam-modal').removeClass('show');
            }
        },
        error: function (xhr) {
            // 恢复按钮状态
            $this.html(originalBtnContent).attr('disabled', false);

            alert("生成失败：" + (xhr.responseJSON ? xhr.responseJSON.msg : "网络错误"));
        }
    });
});

//浏览试卷
$(".examContentBox tbody").on("click",".preview",function() {
    $('#exam-preview-modal').addClass('show');
    var examId = $(this).attr('index');
    $('#download-word-btn').attr('index', examId)
    //浏览试卷
    loadExamPaper(examId);

})

// 加载试卷数据
function loadExamPaper(examId) {
    $.ajax({
        url: "/examPaper/selectById",
        type: "POST",
        data: { id: examId },
        dataType: "json",
        beforeSend: function() {
            // 显示加载中提示
            $('#exam-preview-content').html('<div class="loading">加载试卷中...</div>');
        },
        success: function(response) {
            if (response.code === "0000" && response.data) {
                // 渲染试卷内容
                renderExamPaper(response.data);
            } else {
                $('#exam-preview-content').html('<div class="error">获取试卷失败：' + (response.msg || '未知错误') + '</div>');
            }
        },
        error: function() {
            $('#exam-preview-content').html('<div class="error">网络错误，无法获取试卷</div>');
        }
    });
}

// 渲染试卷内容
function renderExamPaper(exam) {
    // 1. 强制设置容器样式，确保滚动条能正常工作
    const modalContent = document.querySelector('#exam-preview-modal .modal-content');
    if (modalContent) {
        modalContent.style.height = '700px';
        modalContent.style.maxHeight = '700px';
        modalContent.style.display = 'flex';
        modalContent.style.flexDirection = 'column';
        modalContent.style.overflow = 'hidden';
    }

    const contentContainer = document.querySelector('#exam-preview-content');
    if (contentContainer) {
        contentContainer.style.overflowY = 'auto';
        contentContainer.style.flex = '1';
        contentContainer.style.boxSizing = 'border-box';
    }

    // 2. 构建试卷内容HTML
    var contentHtml = '';

    // 试卷标题区域
    contentHtml += '<div class="exam-header">';
    contentHtml += '<h2 class="text-center">' + (exam.examName || '未命名试卷') + '</h2>';
    contentHtml += '<div class="exam-info mt-3 mb-4">';
    contentHtml += '<p><strong>考试时长：</strong>' + (exam.examDuration || 0) + '分钟</p>';
    contentHtml += '<p><strong>试卷描述：</strong>' + (exam.description || '无描述') + '</p>';
    contentHtml += '</div></div>';

    // 选择题部分
    if (exam.choiceQuestions) {
        try {
            var choiceQuestions = JSON.parse(exam.choiceQuestions);
            if (choiceQuestions.length > 0) {
                contentHtml += '<div class="question-section mb-5">';
                contentHtml += '<h3 class="section-title">一、选择题（共' + choiceQuestions.length + '题）</h3>';
                contentHtml += formatChoiceQuestions(choiceQuestions);
                contentHtml += '</div>';
            }
        } catch (e) {
            console.error('解析选择题失败:', e);
            contentHtml += '<div class="error">选择题格式错误</div>';
        }
    }

    // 填空题部分
    if (exam.fillQuestions) {
        try {
            var fillQuestions = JSON.parse(exam.fillQuestions);
            if (fillQuestions.length > 0) {
                contentHtml += '<div class="question-section mb-5">';
                contentHtml += '<h3 class="section-title">二、填空题（共' + fillQuestions.length + '题）</h3>';
                contentHtml += formatFillQuestions(fillQuestions);
                contentHtml += '</div>';
            }
        } catch (e) {
            console.error('解析填空题失败:', e);
            contentHtml += '<div class="error">填空题格式错误</div>';
        }
    }

    // 判断题部分
    if (exam.judgeQuestions) {
        try {
            var judgeQuestions = JSON.parse(exam.judgeQuestions);
            if (judgeQuestions.length > 0) {
                contentHtml += '<div class="question-section mb-5">';
                contentHtml += '<h3 class="section-title">三、判断题（共' + judgeQuestions.length + '题）</h3>';
                contentHtml += formatJudgeQuestions(judgeQuestions);
                contentHtml += '</div>';
            }
        } catch (e) {
            console.error('解析判断题失败:', e);
            contentHtml += '<div class="error">判断题格式错误</div>';
        }
    }

    // 简答题部分
    if (exam.essayQuestions) {
        try {
            var essayQuestions = JSON.parse(exam.essayQuestions);
            if (essayQuestions.length > 0) {
                contentHtml += '<div class="question-section mb-5">';
                contentHtml += '<h3 class="section-title">四、简答题（共' + essayQuestions.length + '题）</h3>';
                contentHtml += formatEssayQuestions(essayQuestions);
                contentHtml += '</div>';
            }
        } catch (e) {
            console.error('解析简答题失败:', e);
            contentHtml += '<div class="error">简答题格式错误</div>';
        }
    }

    // 计算题部分
    if (exam.calculateQuestions) {
        try {
            var calculateQuestions = JSON.parse(exam.calculateQuestions);
            if (calculateQuestions.length > 0) {
                contentHtml += '<div class="question-section mb-5">';
                contentHtml += '<h3 class="section-title">五、计算题（共' + calculateQuestions.length + '题）</h3>';
                contentHtml += formatCalculateQuestions(calculateQuestions);
                contentHtml += '</div>';
            }
        } catch (e) {
            console.error('解析计算题失败:', e);
            contentHtml += '<div class="error">计算题格式错误</div>';
        }
    }

    // 如果没有任何题目
    if (contentHtml.indexOf('question-section') === -1 && contentHtml.indexOf('error') === -1) {
        contentHtml += '<div class="no-questions text-center">该试卷暂无题目内容</div>';
    }

    // 3. 渲染内容到容器
    $('#exam-preview-content').html(contentHtml);

    // 4. 再次强制触发布局重绘，确保滚动条生效
    setTimeout(() => {
        if (contentContainer) {
            contentContainer.scrollTop = 0; // 滚动到顶部
            // 强制重绘
            contentContainer.style.display = 'none';
            contentContainer.offsetHeight; // 触发重绘
            contentContainer.style.display = 'block';
        }
    }, 0);

    // 强制触发重绘（关键修复）
    const content = document.querySelector('#exam-preview-content');
    if (content) {
        // 隐藏 -> 显示，强制浏览器重新计算布局
        content.style.display = 'none';
        void content.offsetWidth; // 触发重绘
        content.style.display = 'block';
    }
}


// 格式化选择题
function formatChoiceQuestions(questions) {
    var html = '';
    questions.forEach(function(question, index) {
        html += '<div class="question-item mb-3">';
        // 题目内容（保留数据库原有格式）
        html += '<p class="question-content"><span class="question-number">' + (index + 1) + '.</span> ' +
            replaceNewlines(question.content) + ' <span class="question-score">(' + question.score + '分)</span></p>';

        html += '<div class="question-options mt-2">';
        if (question.options && question.options.length > 0) {
            question.options.forEach(function(option) {
                // 直接使用数据库中的选项（已包含ABCD前缀）
                html += '<div class="option-item">' + replaceNewlines(option) + '</div>';
            });
        }
        html += '</div></div>';
    });
    return html;
}

// 格式化填空题
function formatFillQuestions(questions) {
    var html = '';
    questions.forEach(function(question, index) {
        html += '<div class="question-item mb-3">';
        html += '<p class="question-content"><span class="question-number">' + (index + 1) + '.</span> ' +
            replaceNewlines(question.content) + ' <span class="question-score">(' + question.score + '分)</span></p>';
        html += '</div>';
    });
    return html;
}

// 格式化判断题
function formatJudgeQuestions(questions) {
    var html = '';
    questions.forEach(function(question, index) {
        html += '<div class="question-item mb-3">';
        html += '<p class="question-content"><span class="question-number">' + (index + 1) + '.</span> ' +
            replaceNewlines(question.content) + ' <span class="question-score">(' + question.score + '分)</span></p>';
        html += '</div>';
    });
    return html;
}

// 格式化简答题
function formatEssayQuestions(questions) {
    var html = '';
    questions.forEach(function(question, index) {
        html += '<div class="question-item mb-3">';
        html += '<p class="question-content"><span class="question-number">' + (index + 1) + '.</span> ' +
            replaceNewlines(question.content) + ' <span class="question-score">(' + question.score + '分)</span></p>';
        html += '<div class="answer-space mt-1">（答题区域）</div>';
        html += '</div>';
    });
    return html;
}

// 格式化计算题
function formatCalculateQuestions(questions) {
    var html = '';
    questions.forEach(function(question, index) {
        html += '<div class="question-item mb-3">';
        html += '<p class="question-content"><span class="question-number">' + (index + 1) + '.</span> ' +
            replaceNewlines(question.content) + ' <span class="question-score">(' + question.score + '分)</span></p>';
        html += '<div class="answer-space mt-1">（答题区域）</div>';
        html += '</div>';
    });
    return html;
}

// 替换换行符为HTML的br标签
function replaceNewlines(text) {
    if (!text) return '';
    return text.replace(/\r\n/g, '<br>').replace(/\n/g, '<br>');
}


//关闭弹框
$('#exam-preview-modal .close-modal,#close-modal-btn').click(function() {
    $('#exam-preview-modal').removeClass('show');
});

//下载Word版
$('#exam-preview-modal #download-word-btn').click(function() {
    var examId = $(this).attr('index');
    if (!examId) {
        alert("未获取到试卷ID，请刷新页面重试");
        return;
    }
    // 2. 保存按钮原始状态（核心：记录原始 HTML 和禁用状态）
    var $btn = $(this);
    var originalHtml = $btn.html();   // 记录原始按钮内容（含图标+文字）
    var isDisabled = $btn.prop('disabled'); // 理论上初始是 false

    // 3. 显示「下载中」状态
    $btn.html('<i class="fas fa-spinner fa-spin"></i> 下载中...').prop('disabled', true);

    // 4. 发起 AJAX 请求（文件流）
    $.ajax({
        url: "/examPaper/downloadWord",  // 后端接口地址
        type: "GET",                     // 与 @GetMapping 对应
        data: { paperId: examId },       // 传递试卷 ID
        xhrFields: {
            responseType: "blob"         // 关键：指定响应为二进制文件流
        },
        success: function(blob, status, xhr) {
            // 5. 解析文件名（从响应头）
            var contentDisposition = xhr.getResponseHeader("Content-Disposition");
            var fileName = "试卷.docx";

            // 处理编码问题（兼容后端返回的中文文件名）
            if (contentDisposition) {
                var match = contentDisposition.match(/filename="(.*?)"/);
                if (match && match[1]) {
                    // 解码文件名（处理 UTF-8 编码）
                    fileName = decodeURIComponent(escape(match[1]));
                }
            }

            // 6. 触发浏览器下载
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement("a");
            a.href = url;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();

            // 7. 清理临时资源
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);

            // 8. 提示成功 + 恢复按钮状态
            alert("下载成功！");
            $btn.html(originalHtml).prop('disabled', isDisabled);
        },
        error: function(xhr) {
            // 9. 处理失败场景
            var errorMsg = "下载失败，请重试";
            try {
                // 尝试解析后端返回的错误信息（如果有）
                var res = JSON.parse(xhr.responseText);
                errorMsg = res.msg || errorMsg;
            } catch (e) {
                // 解析失败则用默认提示
            }
            alert(errorMsg);

            // 10. 恢复按钮状态（失败也要恢复）
            $btn.html(originalHtml).prop('disabled', isDisabled);
        }
    });
});

//发布考试弹框
$(".examContentBox tbody").on("click",".publish",function() {
    $('#publish-exam-modal').addClass('show');
    var examId = $(this).attr('index');
    $('#public-exam').attr('index', examId)

})


//发布考试
$('#public-exam').click(function(){
    var examId = $(this).attr('index');
    // 获取发布时间的值
    var rawPublishTime = $("#exam-publish-time").val();
    // 获取考试时长的值
    var duration = $("#exam-duration-min").val();
    var publishTime = rawPublishTime.replace('T', ' ') + ':00';
    var publishData={
        id:parseInt(examId, 10),
        releaseTime:publishTime,
        examDuration:parseInt(duration, 10)
    }
    console.log(publishData)
    $.ajax({
        url: "/exam/publish",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(publishData),
        success: function(value) {
            alert(value.msg);
            if (value.code == "0000") {
                $('#publish-exam-modal').removeClass('show');

            }
        },
        error: function() {
            alert("发布失败");
        }
    });
})

//关闭考试弹框
$('#publish-exam-modal .close-modal,#public-cancel').click(function() {
    $('#publish-exam-modal').removeClass('show');
});

//页码切换
//任意页码切换
$(".examPageBox").on("click", ".page1", function() {
    if (isSearch == 0) {
        if (examPage == $(this).text()) {
            alert("该页已经是第" + $(this).text() + "页");
            return;
        }
        examPage = $(this).text();
    } else {
        if (serPage == $(this).text()) {
            alert("该页已经是第" + $(this).text() + "页");
            return;
        }
        serPage = $(this).text();
    }
    exData();
    $(this).addClass("active");
    $(this).siblings().removeClass("active");
});

//上一页切换
$(".examPageBox").on("click", ".prevPage", function() {
    if (isSearch == 0) {
        if (examPage == 1) {
            alert("已经是第一页");
            return;
        }
        examPage--;
    } else {
        if (serPage == 1) {
            alert("已经是第一页");
            return;
        }
        serPage--;
    }
    exData();
    $(".examPageBox .page1").removeClass("active");
    //索引从0开始，page从1开始
    if (isSearch == 0) {
        $(".examPageBox .page1").eq(examPage - 1).addClass("active");
    } else {
        $(".examPageBox .page1").eq(serPage - 1).addClass("active");
    }
});

//下一页切换
$(".examPageBox").on("click", ".nextPage", function() {
    if (isSearch == 0) {
        if (examPage == $(".examPageBox .page1").length) {
            alert("已经是最后一页");
            return;
        }
        examPage++;
    } else {
        if (serPage == $(".examPageBox .page1").length) {
            alert("已经是最后一页");
            return;
        }
        serPage++;
    }
    exData();
    $(".examPageBox .page1").removeClass("active");
    if (isSearch == 0) {
        $(".examPageBox .page1").eq(examPage - 1).addClass("active");
    } else {
        $(".examPageBox .page1").eq(serPage - 1).addClass("active");
    }
});

//考试搜索
$("#exam-management .search-boxes #search-tp-btn").click(function() {
    console.log("成功了")
    //搜索状态设置为1
    isSearch = 1;
    //读取 搜索框的输入
    var createByName = $('#search-tp-name').val().trim();
    if(createByName==""){
        alert("请输入教案名称")
    }
    var offset = (serPage - 1) * pageSize;
    examData = {
        "createByName": createByName,
        "offset":offset,
        "pageSize": pageSize
    };

    exPage();
    exData();
});

$(document).ready(function() {
    // 页面加载时获取当前登录教师信息
    fetchTeacherInfo();

    // 点击用户名显示弹窗
    $("#username").on("click", function() {
        $("#userModal").css("display", "flex");
        // 刷新个人信息
        fetchTeacherDetail();
    });

    // 点击关闭按钮关闭弹窗
    $(".close-modal").on("click", function() {
        $("#userModal").hide();
    });

    // 点击弹窗外部关闭
    $(window).on("click", function(e) {
        if ($(e.target).hasClass("teacher-modal")) {
            $("#userModal").hide();
        }
    });

    // 退出登录功能
    $("#logoutBtn").on("click", function() {
        if (confirm("确定要退出登录吗？")) {
            $.ajax({
                url: "/user/logout", // 教师退出登录接口
                type: "POST",
                dataType: "json",
                success: function(response) {
                    if (response.code === "0000") {
                        // 退出成功，跳转到登录页
                        window.location.href = "/LLMTchStd/userlogin";
                    } else {
                        alert("退出失败：" + (response.msg || "未知错误"));
                    }
                },
                error: function(xhr) {
                    console.error("退出登录请求失败", xhr);
                    alert("网络错误，退出失败");
                }
            });
        }
    });
});

/**
 * 获取当前登录教师的基本信息（用于显示用户名）
 */
function fetchTeacherInfo() {
    $.ajax({
        url: "/user/teacherCurrent", // 后端获取当前教师信息接口
        type: "GET",
        dataType: "json",
        success: function(response) {
            if (response.code === "0000" && response.data) {
                // 更新用户名显示（假设后端返回name字段）
                $("#username").text(response.data.name || "未知教师");
            } else {
                console.error("获取教师信息失败", response.msg);
                $("#username").text("未登录");
            }
        },
        error: function(xhr) {
            console.error("获取教师信息请求失败", xhr);
            $("#username").text("加载失败");
        }
    });
}

/**
 * 获取教师详细信息（用于弹窗展示）
 */
function fetchTeacherDetail() {
    $.ajax({
        url: "/user/teacherCurrent", // 后端获取教师详细信息接口
        type: "GET",
        dataType: "json",
        success: function(response) {
            if (response.code === "0000" && response.data) {
                const teacher = response.data;
                // 渲染教师详细信息
                let infoHtml = `
                    <div class="info-item"><strong>姓名：</strong><span>${teacher.name || "未设置"}</span></div>
                    <div class="info-item"><strong>性别：</strong><span>${teacher.sex || "未设置"}</span></div>
                    <div class="info-item"><strong>工号：</strong><span>${teacher.workNo || "未设置"}</span></div>
                    <div class="info-item"><strong>联系电话：</strong><span>${teacher.phone || "未设置"}</span></div>
                `;
                $("#teacherInfo").html(infoHtml);
            } else {
                $("#teacherInfo").html(`<div class="loading">获取信息失败：${response.msg || "未知错误"}</div>`);
            }
        },
        error: function(xhr) {
            console.error("获取教师详细信息请求失败", xhr);
            $("#teacherInfo").html(`<div class="loading">网络错误，无法获取信息</div>`);
        }
    });
}